<?php
   require("Util.php");
  $folder_name = $_GET["templateFile"];
  $folderpath = $GLOBALS['uploaddir']."/".$folder_name;
  echo "zipping ".$folderpath."<br />";
  $now = time();
  header("Content-Type: application/force-download");
  header('Content-Disposition: attachment;
   filename="ZIPfileName'.$now.'_Download.zip"');
  exec("zip ".$now."_archive.zip ".$folderpath."/* 2>&1", $output);
  readfile($now."_archive.zip"); 

  compress($folderpath,$folder_name);

  function recurse_zip($src,&$zip,$path_length) {
        $dir = opendir($src);
        while(false !== ( $file = readdir($dir)) ) {
            if (( $file != '.' ) && ( $file != '..' )) {
                if ( is_dir($src . '/' . $file) ) {
                    recurse_zip($src . '/' . $file,$zip,$path_length);
                }
                else {
                    $zip->addFile($src . '/' . $file,substr($src . '/' . $file,$path_length));
                }
            }
        }
        closedir($dir);
  }
//Call this function with argument = absolute path of file or directory name.
function compress($src,$zip_name)
{
        if(substr($src,-1)==='/'){
						$src=substr($src,0,-1);
				}
        $arr_src=explode('/',$src);
        $filename=end($src);
        unset($arr_src[count($arr_src)-1]);
        $path_length=strlen(implode('/',$arr_src).'/');
        $ndir = $GLOBALS['uploaddir']."/archive";
        if (!file_exists($ndir)) {
					makeFolder($ndir, 0777);
				}
				$filename=$ndir."/".$zip_name.'.zip';
				echo "compressing ".$src." to ".$filename."<br />";
        $zip = new ZipArchive;
        $res = $zip->open($filename, ZipArchive::CREATE);
        if($res !== TRUE){
                echo 'Error: Unable to create zip file';
                exit;}
        if(is_file($src)){
					$zip->addFile($src,substr($src,$path_length));
				} else {
                if(!is_dir($src)){
                     $zip->close();
                     @unlink($filename);
                     echo 'Error: File not found';
                     exit;
								}
        recurse_zip($src,$zip,$path_length);}
        $zip->close();
        header("Location: $filename");
        exit;
}
?>